<template>
  <div class="image-converter">
    <div class="container">
      <h1>图片格式转换</h1>
      <el-card>
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="upload-area" @click="triggerUpload" @dragover.prevent @drop.prevent="handleDrop">
              <el-icon class="upload-icon"><Upload /></el-icon>
              <div class="upload-text">点击上传，或将图片拖拽到此处</div>
              <input type="file" ref="fileInput" class="hidden-input" @change="handleFileChange" accept="image/*">
            </div>
            <el-button type="primary" class="convert-btn" @click="convertAndDownload" :disabled="!imageInfo">
              <el-icon><Download /></el-icon>
              开始转换并下载
            </el-button>
          </el-col>
          <el-col :span="12">
            <el-form label-width="100px" class="image-info" v-if="imageInfo">
              <el-form-item label="转换格式">
                <el-select v-model="convertFormat" placeholder="请选择">
                  <el-option label="JPG" value="image/jpeg"></el-option>
                  <el-option label="PNG" value="image/png"></el-option>
                  <el-option label="WEBP" value="image/webp"></el-option>
                  <el-option label="BMP" value="image/bmp"></el-option>
                  <el-option label="GIF" value="image/gif"></el-option>
                  <el-option label="ICO" value="image/x-icon"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <el-table :data="imageInfoTable" border v-if="imageInfo">
              <el-table-column prop="attribute" label="图片属性"></el-table-column>
              <el-table-column prop="value" label="值"></el-table-column>
              <el-table-column prop="description" label="描述"></el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-card>
      <div class="description">
        <h3>关于图片格式转换介绍：</h3>
        <ol>
          <li>此工具可以将任意格式的图片转为png,jpeg,webp,bmp,gif,ico等格式。</li>
          <li>先上传图片本地图片，并会显示图片的基础信息。</li>
          <li>选择你要转换的格式，比如png,jpeg...</li>
          <li>点击"开始转换并下载"按钮即可下载转换后的图片。</li>
          <li>注意：本工具只在前台运行，不会将您上传的图片上传至服务器，请放心使用。</li>
        </ol>
      </div>
      <div class="button-group">
        <el-button type="warning" @click="goToHomepage">
          <el-icon><Back /></el-icon>
          返回
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Upload, Download, Back } from '@element-plus/icons-vue'

const router = useRouter()
const imageInfo = ref(null)
const convertFormat = ref('')
const imageFile = ref(null)
const imageInfoTable = ref([])
const fileInput = ref(null)

const triggerUpload = () => {
  fileInput.value.click()
}

const handleDrop = (event) => {
  const file = event.dataTransfer.files[0]
  if (file && file.type.startsWith('image/')) {
    handleFile(file)
  } else {
    ElMessage.error('请上传图片文件')
  }
}

const handleFileChange = (event) => {
  const file = event.target.files[0]
  if (file) {
    handleFile(file)
  }
}

const handleFile = (file) => {
  imageFile.value = file
  const reader = new FileReader()
  reader.onload = (e) => {
    const img = new Image()
    img.onload = () => {
      imageInfo.value = {
        size: (file.size / 1024).toFixed(2),
        type: file.type,
        width: img.width,
        height: img.height
      }
      updateImageInfoTable()
    }
    img.src = e.target.result
  }
  reader.readAsDataURL(file)
}

const updateImageInfoTable = () => {
  imageInfoTable.value = [
    { attribute: '图片大小', value: imageInfo.value.size + ' KB', description: '单位：KB' },
    { attribute: '图片类型', value: imageInfo.value.type.split('/')[1], description: '如：jpg' },
    { attribute: '图片宽度', value: imageInfo.value.width + ' px', description: '单位：px' },
    { attribute: '图片高度', value: imageInfo.value.height + ' px', description: '单位：px' }
  ]
}

const convertAndDownload = () => {
  if (!imageFile.value || !convertFormat.value) {
    ElMessage.error('请上传图片并选择转换格式')
    return
  }

  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  const img = new Image()

  img.onload = () => {
    if (convertFormat.value === 'image/x-icon') {
      canvas.width = 32
      canvas.height = 32
      ctx.drawImage(img, 0, 0, 32, 32)
      
      canvas.toBlob(blob => {
        const reader = new FileReader()
        reader.onload = () => {
          const arr = new Uint8Array(reader.result)
          const header = new Uint8Array([0, 0, 1, 0, 1, 0, 32, 32, 0, 0, 1, 0, 32, 0, 0, 0, 0, 0])
          const iconData = new Uint8Array(header.length + arr.length)
          iconData.set(header, 0)
          iconData.set(arr, header.length)
          const iconBlob = new Blob([iconData], {type: 'image/x-icon'})
          downloadBlob(iconBlob, 'converted.ico')
        }
        reader.readAsArrayBuffer(blob)
      }, 'image/png')
    } else {
      canvas.width = img.width
      canvas.height = img.height
      ctx.drawImage(img, 0, 0)
      canvas.toBlob(blob => {
        downloadBlob(blob, `converted.${convertFormat.value.split('/')[1]}`)
      }, convertFormat.value)
    }
  }

  img.src = URL.createObjectURL(imageFile.value)
}

const downloadBlob = (blob, fileName) => {
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = fileName
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

const goToHomepage = () => {
  router.push('/')
}
</script>

<style lang="scss" scoped>
.image-converter {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 10px;

  .container {
    max-width: 1200px;
    width: 98%;
    background-color: rgba(255, 255, 255, 0.95);
    border-radius: 20px;
    box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
    padding: 25px;
    box-sizing: border-box;

    h1 {
      text-align: center;
      color: #4a5568;
      font-size: 2.5em;
      margin: 0 0 25px 0;
      text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
    }

    .upload-area {
      border: 2px dashed #ff7503;
      border-radius: 12px;
      text-align: center;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      padding: 40px 20px;
      transition: all 0.3s ease;

      &:hover {
        border-color: #409EFF;
        background-color: rgba(64, 158, 255, 0.05);
      }

      .upload-icon {
        font-size: 48px;
        color: #8c939d;
        margin-bottom: 10px;
      }

      .upload-text {
        color: #97a8be;
        font-size: 14px;
      }
    }

    .convert-btn {
      width: 100%;
      margin-top: 20px;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;

      .el-icon {
        margin-right: 8px;
      }
    }

    .image-info {
      margin-bottom: 20px;
    }

    .description {
      background-color: #fdf6ec;
      border: 1px solid #faecd8;
      padding: 20px;
      border-radius: 10px;
      margin: 20px 0;
      text-align: left;

      h3 {
        color: #e6a23c;
        margin: 0 0 15px 0;
        font-size: 1.2em;
      }

      ol {
        margin: 0;
        padding-left: 20px;
        color: #666;

        li {
          margin-bottom: 10px;
          line-height: 1.5;

          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }

    .button-group {
      display: flex;
      justify-content: center;
      gap: 15px;

      .el-button {
        min-width: 120px;
        display: flex;
        align-items: center;
        justify-content: center;

        .el-icon {
          margin-right: 6px;
        }

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
      }
    }

    .hidden-input {
      display: none;
    }
  }
}

@media (max-width: 768px) {
  .image-converter {
    padding: 10px;

    .container {
      padding: 15px;

      h1 {
        font-size: 24px;
        margin-bottom: 20px;
      }

      .el-row {
        display: block;

        .el-col {
          width: 100%;
          margin-bottom: 20px;
        }
      }

      .upload-area {
        padding: 20px;
      }

      .button-group {
        flex-direction: column;
        gap: 10px;

        .el-button {
          width: 100%;
        }
      }
    }
  }
}
</style>
